using MediatR;
using Medical.Domain;
using Medical.Infrastructrue.Interfaces;
using Medical.ReadApi.Dto;
using Medical.WriteApi.Appcontext.Command;
using Medical.WriteApi.Appcontext.Command.OutpatientOrderTemplates;
using Medical.WriteApi.Dto;
using Microsoft.EntityFrameworkCore;
using Yitter.IdGenerator;

namespace Medical.WriteApi.Appcontext.CommandHandler
{
	public class CreateOutpatientOrderTemplateCommandHandler : IRequestHandler<CreateOutpatientOrderTemplateCommand, OutpatientOrderTemplateDto>
	{
		private readonly IBaseRepository<OutpatientOrderTemplate> _repository;

		public CreateOutpatientOrderTemplateCommandHandler(IBaseRepository<OutpatientOrderTemplate> repository)
		{
			_repository = repository;
		}

		public async Task<OutpatientOrderTemplateDto> Handle(CreateOutpatientOrderTemplateCommand request, CancellationToken cancellationToken)
		{
			// 验证模板名称
			if (string.IsNullOrWhiteSpace(request.TemplateName))
			{
				throw new ArgumentException("模板名称不能为空", nameof(request.TemplateName));
			}

			// 检查模板名称是否已存在
			var existingTemplate = await _repository.GetModel(x => 
				x.TemplateName == request.TemplateName && !x.IsDeleted);
			if (existingTemplate != null)
			{
				throw new InvalidOperationException($"模板名称 '{request.TemplateName}' 已存在");
			}

			// 如果设置为默认模板，需要将其他默认模板取消默认状态
			if (request.IsDefault)
			{
				var defaultTemplates = await _repository.GetAll()
					.Where(x => x.IsDefault && !x.IsDeleted)
					.ToListAsync(cancellationToken);
				
				if (defaultTemplates.Any())
				{
					foreach (var template in defaultTemplates)
					{
						template.IsDefault = false;
						template.UpdatedAt = DateTime.Now;
					}
					await _repository.UpdateRangeAsync(defaultTemplates);
				}
			}

			var entity = new OutpatientOrderTemplate
			{
				TemplateId = YitIdHelper.NextId(),
				TemplateName = request.TemplateName.Trim(),
				Description = request.Description,
				IsActive = request.IsActive,
				IsDefault = request.IsDefault,
				ShowSerialNumber = request.ShowSerialNumber,
				ShowDepartment = request.ShowDepartment,
				ShowDoctor = request.ShowDoctor,
				ShowPrescription = request.ShowPrescription,
				ShowBedNumber = request.ShowBedNumber,
				ShowConsultationTime = request.ShowConsultationTime,
				ShowAdmissionTime = request.ShowAdmissionTime,
				ShowDischargeTime = request.ShowDischargeTime,
				ShowExpenseDetails = request.ShowExpenseDetails,
				ShowCashier = request.ShowCashier,
				ShowAmount = request.ShowAmount,
				IsDeleted = false,
				CreatedAt = DateTime.Now,
				UpdatedAt = DateTime.Now
			};

			await _repository.InsertAsync(entity);

			return new OutpatientOrderTemplateDto
			{
				TemplateId = entity.TemplateId,
				TemplateName = entity.TemplateName,
				Description = entity.Description,
				IsActive = entity.IsActive,
				IsDefault = entity.IsDefault,
				ShowSerialNumber = entity.ShowSerialNumber,
				ShowDepartment = entity.ShowDepartment,
				ShowDoctor = entity.ShowDoctor,
				ShowPrescription = entity.ShowPrescription,
				ShowBedNumber = entity.ShowBedNumber,
				ShowConsultationTime = entity.ShowConsultationTime,
				ShowAdmissionTime = entity.ShowAdmissionTime,
				ShowDischargeTime = entity.ShowDischargeTime,
				ShowExpenseDetails = entity.ShowExpenseDetails,
				ShowCashier = entity.ShowCashier,
				ShowAmount = entity.ShowAmount,
				CreatedAt = entity.CreatedAt,
				UpdatedAt = entity.UpdatedAt
			};
		}
	}
}
